//
//  USOurListDoneAlert.m
//  us
//
//  Created by karry on 2025/5/28.
//

#import "USOurListDoneView.h"
#import "TouchableMaskView.h"
#import "USDateAlertView.h"
#import "USPhotoUploadTool.h"
#import "USMediaUploadManager.h"
#import "USMediaResult.h"
#import <UITextView+Placeholder/UITextView+Placeholder.h>
#import "IQKeyboardManager.h"

@interface USOurListDoneView ()<PHPickerViewControllerDelegate>

@property (nonatomic, strong) UIView *stickerMaskView;

@property (nonatomic, strong) UIButton *doneBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UIButton *fullDoneBtn;

@property (nonatomic, strong) UIImage *pettyImage;
 
@property (nonatomic, assign) BOOL o_enable;
@property (nonatomic, assign) BOOL o_enableAutoToolbar;
@property (nonatomic, assign) CGFloat keyboardDistanceFromTextField;

@end

@implementation USOurListDoneView

- (void)awakeFromNib{
    [super awakeFromNib];
    
    
    self.o_enable = [IQKeyboardManager sharedManager].enable;
    self.o_enableAutoToolbar = [IQKeyboardManager sharedManager].enableAutoToolbar;

    // 临时修改状态
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    
    self.backgroundColor = UIColor.mi_1_color;
    self.layer.cornerRadius = 14;
    self.layer.masksToBounds = YES;
    
    self.imgView.layer.cornerRadius = 14;
    self.imgView.layer.masksToBounds = YES;
    self.imgView.userInteractionEnabled = YES;
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(chooseImg)];
    [self.imgView addGestureRecognizer:recognizer];
    
    [self.imgEditBtn setEnabled:NO];

 
    self.cancelBtn = [UIButton us_borderButtonWithTitle:@"取消打卡"];
    self.cancelBtn.layer.cornerRadius = 14;
    [self.cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.cancelBtn];
 
    self.doneBtn = [UIButton us_fillButtonWithTitle:@"打卡"];
    self.doneBtn.layer.cornerRadius = 14;
    [self.doneBtn addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.doneBtn];
    
    self.fullDoneBtn = [UIButton us_fillButtonWithTitle:@"打卡"];
    self.fullDoneBtn.layer.cornerRadius = 14;
    [self.fullDoneBtn addTarget:self action:@selector(doneAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:self.fullDoneBtn];
 
 
    CGFloat buttonSpacing = 12;
    CGFloat sidePadding = 16;

    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(sidePadding);
        make.right.equalTo(self.doneBtn.mas_left).offset(-buttonSpacing);
        make.height.mas_equalTo(56);
        make.bottom.equalTo(self.mas_safeAreaLayoutGuideBottom);
        make.width.equalTo(self.doneBtn); 
    }];

    [self.doneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-sidePadding);
        make.left.equalTo(self.cancelBtn.mas_right).offset(buttonSpacing);
        make.height.mas_equalTo(56);
        make.bottom.equalTo(self.mas_safeAreaLayoutGuideBottom);
    }];
 
    [self.fullDoneBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-16);
        make.left.mas_equalTo(16);
        make.height.mas_equalTo(56);
        make.bottom.equalTo(self.mas_safeAreaLayoutGuideBottom);
    }];
    
    
    self.titleView.placeholder = @"名称";
    self.titleView.returnKeyType = UIReturnKeyDone;
    
    [self centerTextInTextView:self.titleView.placeholderTextView];//使placeholder居中

    @weakify(self)
    [[self.titleView.rac_textSignal distinctUntilChanged] subscribeNext:^(NSString * _Nullable text) {
        @strongify(self);
        
        // 移除换行符
        if ([text containsString:@"\r"]) {
            text = [text stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            self.titleView.text = text;
        }
        if ([text containsString:@"\n"]) {
            text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            self.titleView.text = text;
            [self.titleView resignFirstResponder];
            return;
        }
        
        // 限制最多20字符
        if (text.length > 20) {
            text = [text substringToIndex:20];
            self.titleView.text = text;
        }
        
        [self centerTextInTextView:self.titleView];
        
    }];
  
    RACSignal *dayValidSignal = [RACObserve(self, itemModel.completionTime) map:^id _Nullable(id value) {
        return @([value integerValue] > 0);
    }];


    // nameTextField 不为空判断
    RACSignal *nameValidSignal = [RACObserve(self.titleView, text) map:^id _Nullable(NSString *text) {
        return @((text.length > 0));
    }];

    [[RACSignal combineLatest:@[dayValidSignal, nameValidSignal]
                       reduce:^id(NSNumber *birthdayValid, NSNumber *nameValid) {
        return @(birthdayValid.boolValue && nameValid.boolValue);
    }]
     subscribeNext:^(NSNumber * _Nullable isEnabled) {
         @strongify(self);
         self.doneBtn.enabled = isEnabled.boolValue;
     }];

}

- (void)centerTextInTextView:(UITextView *)textView {
    // 设置水平居中
    textView.textAlignment = NSTextAlignmentRight;

    // 计算文字高度
    CGSize fittingSize = CGSizeMake(textView.bounds.size.width - textView.textContainerInset.left - textView.textContainerInset.right, CGFLOAT_MAX);
    CGSize size = [textView sizeThatFits:fittingSize];

    CGFloat topOffset = (textView.bounds.size.height - size.height) / 2.0;
    topOffset = MAX(0, topOffset); // 防止负数

    // 设置内容内边距，实现垂直居中
    textView.contentInset = UIEdgeInsetsMake(topOffset, 0, 0, 0);
}


- (void)setItemModel:(USListItemModel *)itemModel {
    _itemModel = itemModel;
     
    self.itemModel.deletePic = NO;

    self.pettyImage = nil;
    if (itemModel.taskPicUrl.length > 0) {
        [self.imgView sd_setImageWithURL:[NSURL URLWithString:itemModel.taskPicUrl]];
        [self.imgEditBtn setEnabled:YES];
    }else{
        self.imgView.image = [UIImage imageNamed:@"list_photo_empty"];
        [self.imgEditBtn setEnabled:NO];
    }
    self.titleView.text = itemModel.taskTitle;
    [self centerTextInTextView:self.titleView];

    
     NSString * dateString = [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:itemModel.completionTime] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    [self.timeBtn setTitle:dateString forState:0];

    if (itemModel.completionStatus) {
        self.fullDoneBtn.hidden = YES;
      
    }else {
        self.fullDoneBtn.hidden = NO;
     }
}

- (void)chooseImg {
    [USFeedbackTool impactSoft];

    PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
    config.selectionLimit = 1; // 只选一张图
    config.filter = [PHPickerFilter imagesFilter]; // 只显示图片

    PHPickerViewController *picker = [[PHPickerViewController alloc] initWithConfiguration:config];
    picker.delegate = self;
    [UIViewController.topViewController presentViewController:picker animated:YES completion:nil];
}


// 代理回调
- (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results {
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    PHPickerResult *result = results.firstObject;
    if (result) {
        [result.itemProvider loadObjectOfClass:[UIImage class] completionHandler:^(UIImage *image, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (image) {
                    // ✅ 使用选中的图片
                    self.imgView.image = image;
                    self.pettyImage = image;
                    
                    [self.imgEditBtn setEnabled:YES];
                    
                }
            });
        }];
    }
}
- (IBAction)deleteAction:(id)sender {
    if (self.listDeleteBlock) {
        self.listDeleteBlock();
        [self hideStickerPicker];
    }
}

- (IBAction)imageEditAction:(id)sender {
    
    [self.imgEditBtn setEnabled:NO];

    if (self.pettyImage) {
        self.pettyImage = nil;
    }
    self.itemModel.deletePic = YES;
//    self.itemModel.taskPicUrl = @"";//此刻不能删除，因为用户没有点确认，防止取消不显示
    self.imgView.image = [UIImage imageNamed:@"list_photo_empty"];

}

- (IBAction)chooseTimeAction:(id)sender {
    
    USDateAlertView *alert = [[USDateAlertView alloc]initWithDate:[NSDate date] andSubTitle:@"设置打卡时间" limitToNow:YES];
    [alert showInView:UIViewController.topViewController.view];
    @weakify(self)
    alert.didChooseBlock = ^(NSDate * _Nonnull date) {
        @strongify(self)
        
        NSTimeInterval timestamp = [date timeIntervalSince1970];
        NSInteger timestampInSeconds = (NSInteger)timestamp;
     
        self.itemModel.completionTime = timestampInSeconds;
        NSString * dateString = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
        [self.timeBtn setTitle:dateString forState:0];
    };
}

- (void)cancelAction {
    if (self.listCancelBlock) {
        self.listCancelBlock();
        [self hideStickerPicker];

    }
}
- (void)doneAction {
    self.itemModel.taskTitle = self.titleView.text?:@"";
    if (self.pettyImage) {
        [EMHudManager show:@"上传中..."];

        [USMediaUploadManager uploadImageToCOS:self.pettyImage progress:^(CGFloat progress) {
            [EMHudManager showProgress: progress];
            [EMHudManager show:[NSString stringWithFormat:@"上传中 %i%%", (int)progress * 100]];
        } success:^(NSString * _Nonnull cosUrl) {
            
            self.itemModel.taskPicUrl = cosUrl;
            NSLog(@"图片上传成功");
            if (self.listDoneBlock) {
                self.listDoneBlock();
                [self hideStickerPicker];

            }
        } failure:^(NSError * _Nonnull error) {
            
        }];
    }else{
        if (self.listDoneBlock) {
            self.listDoneBlock();
            [self hideStickerPicker];

        }
    }
  
    
}
 
- (void)showLitPickerWithAllowTapDismiss:(BOOL)allowDismiss {
    
    if (self.hidden != YES) {
        return;
    }
        
    self.hidden = NO;
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(0);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        [self.superview layoutIfNeeded];
    }completion:^(BOOL finished) {

    }];
    
    //允许点击背景消失
    if (allowDismiss) {
        if (!self.stickerMaskView) {
            //可以让当前view消失，而且不影响后面的点击事件
            TouchableMaskView *maskView = [[TouchableMaskView alloc] initWithFrame:self.superview.bounds];
            maskView.backgroundColor = UIColor.clearColor;
            maskView.userInteractionEnabled = YES;
            @weakify(self)
            maskView.onTapOutside = ^{
                @strongify(self)
                [self hideStickerPicker];
            };
            _stickerMaskView = maskView;
        }
        [self.superview insertSubview:self.stickerMaskView belowSubview:self];
    }
    
}


- (void)hideStickerPicker{
    [self.titleView resignFirstResponder];

    if (self.stickerMaskView) {
        [self.stickerMaskView removeFromSuperview];
        self.stickerMaskView = nil;
    }
    
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_offset(self.jk_height);
    }];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.superview layoutIfNeeded];
    }completion:^(BOOL finished) {
        self.hidden = YES;
    }];
    
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    [super willMoveToSuperview:newSuperview];

    if (newSuperview) {
        // 保存原状态
        self.o_enable = [IQKeyboardManager sharedManager].enable;
        self.o_enableAutoToolbar = [IQKeyboardManager sharedManager].enableAutoToolbar;
        self.keyboardDistanceFromTextField = [IQKeyboardManager sharedManager].keyboardDistanceFromTextField;

        // 临时修改状态
        [IQKeyboardManager sharedManager].enable = YES;
        [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
        [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = 20;

    } else {
        // 离开时不用处理，在 didMoveToSuperview 中统一恢复
    }
}

- (void)didMoveToSuperview {
    [super didMoveToSuperview];
    if (!self.superview) {
        // 恢复原状态
        [IQKeyboardManager sharedManager].enable = self.o_enable;
        [IQKeyboardManager sharedManager].enableAutoToolbar = self.o_enableAutoToolbar;
        [IQKeyboardManager sharedManager].keyboardDistanceFromTextField = self.keyboardDistanceFromTextField;
    }
}


@end
